package bing.netty.example.discard;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.ReferenceCountUtil;
import io.netty.buffer.ByteBuf;
/**
 * Handles a server-side channel.
 */
public class DiscardServerHandler extends ChannelInboundHandlerAdapter{

	@Override
	public void channelRead(ChannelHandlerContext ctx,Object msg){
		//1.DisCard the received data silently
		//((ByteBuf)msg).release();
		
		/*
		 * 2. 不处理接收到的信息
		try{
			//do something with msg
		}finally{
			ReferenceCountUtil.release(msg);
		}
		*/
		
		//3. 把接收到的信息直接打印出来，
		//启动DiscardServer类，使用命令行--telnet localhost 8030,发送信息，此处处理接收到的消息
		/*
		ByteBuf in = (ByteBuf) msg;
	    try {
	        while (in.isReadable()) { // (1)
	            System.out.print((char) in.readByte());
	            System.out.flush();
	        }
	    } finally {
	        ReferenceCountUtil.release(msg); // (2)
	    }
	    */
		
		//4.返回接收到的消息
	    ctx.write(msg); // (1)
	    ctx.flush(); // (2)
	}
	
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx,Throwable cause){
		cause.printStackTrace();
		ctx.close();
	}
}
